import {uSelectUserDevList} from '@/api/public'
import {getUserId} from '@/libs/auth'

export const DeviceSelect = defineComponent({
  props: {
    value: Number,
    max: Number,
    lazy: {
      type: Boolean,
      default: true
    },
    isDevId: Boolean,
    currentName: String
  },
  emits: {
    'update:value': (str?: number): boolean => true
  },
  setup(props, {emit}) {
    const state = reactive<{
      devList: DeviceData[]
      currentDevId: number | undefined
      currentDevName: string | undefined | null
    }>({
      currentDevId: undefined,
      devList: [],
      currentDevName: null
    })

    function getDevList(cb?: (data: DeviceData[]) => void) {
      const userId = getUserId()
      if (!userId) return
      uSelectUserDevList({userId})
        .then(res => {
          // let newArr = []
          // res.data.forEach((item) => {
          //   newArr.push()
          // })
          state.devList = res.data
          console.log(state.devList)

          cb && cb(res.data)
        })
        .catch(err => {})
    }

    const searchSelectsChange = () => {
      state.devList.forEach(item => {
        if (item.devName == state.currentDevName) {
          state.currentDevId = item.devId
        }
      })
    }

    watch(
      () => props.value,
      n => {
        state.currentDevId = n
      },
      {immediate: true}
    )

    watch(
      () => state.currentDevId,
      n => {
        emit('update:value', n)
      }
    )

    onMounted(() => {
      console.log(props.isDevId, 'isDevId')
      state.currentDevName = props.currentName
      if (!props.lazy) {
        if (state.currentDevName == '') {
          // if (!props.isDevId) {
          getDevList(data => {
            emit('update:value', data[0].devId)
          })
        }
        // }
      }
    })

    return () => (
      <a-select
        allowClear
        show-search
        placeholder='下拉选择'
        class={['w-190 h-full', (state.currentDevId ?? null) === null ? 'bg-select' : '']}
        v-model={[state.currentDevName, 'value']}
        options={state.devList}
        fieldNames={{
          label: 'devName',
          value: 'devName'
        }}
        onFocus={() => {
          getDevList()
        }}
        onChange={() => {
          searchSelectsChange()
        }}
      ></a-select>
    )
  }
})
